<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
    >
      <template slot-scope="" slot="operatornameSearch">
        <el-input placeholder="请选择 操作人员" readonly="true" v-model="search.operatorName">
          <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/cloud/cloud_transaction';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  name: 'CloudCloudTransaction',
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {}, //搜索条件
      selectionList: [],
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        dialogClickModal: false,
        addBtn: false, //新增按钮是否显示
        menu: false, //表格操作栏是否显示
        searchSpan: 4,
        column: [
          {
            label: '事务时间',
            prop: 'transactionTime',
            search: true,
            searchOrder: 7,
            searchSpan: 8,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '事务类型',
            prop: 'transactionType',
            search: true,
            searchOrder: 3,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=transaction_type'
          },
          {
            label: '物料编码',
            prop: 'partCode',
            search: true,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料批次',
            prop: 'lotNo',
            search: true,
            searchOrder: 5
          },
          {
            label: '包装条码',
            prop: 'packNo',
            search: true,
            searchOrder: 6
          },
          {
            label: '库存中心',
            prop: 'inventoryName'
          },
          {
            label: '库存中心',
            prop: 'inventoryId',
            search: true,
            searchOrder: 1,
            type: 'select',
            hide: true,
            dicUrl: '/api/mes-admin/inventory/list',
            props: {
              label: 'name',
              value: 'id'
            },
            cascader: ['areaId']
            // control: (val) => {
            //     console.log(val, 'valval')
            //     this.deptId = val;
            // }
          },
          {
            label: '储位名称',
            prop: 'areaId',
            search: true,
            searchOrder: 2,
            type: 'select',
            hide: true,
            dicFlag: false,
            dicUrl: '/api/mes-admin/area/select/inventory?inventoryId={{key}}',
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '储位名称',
            prop: 'areaName'
          },
          {
            label: '事务数量',
            prop: 'quantity',
            html: true,
            formatter: (val) => {
              if (val.quantity.indexOf('-') != -1) {
                return `<span class="text-green">${val.quantity}</span>`;
              } else {
                return `<span class="text-red">+${val.quantity}</span>`;
              }
            }
          },
          {
            label: '单据号',
            prop: 'sheetNo'
          },
          {
            label: '状态',
            prop: 'status',
            dicData: [
              {
                label: '成功',
                value: 1
              },
              {
                label: '失败',
                value: 0
              }
            ]
          },
          {
            label: '操作人员',
            prop: 'operatorName',
            search: true,
            searchOrder: 8,
            searchType: 'search',
            formslot: true,
            appendClick: () => {
              this.openUserCommonModal();
            }
          }
        ]
      },
      data: [],
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      deptId: ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.transaction_add, false),
        viewBtn: this.vaildData(this.permission.transaction_view, false),
        delBtn: this.vaildData(this.permission.transaction_delete, false),
        editBtn: this.vaildData(this.permission.transaction_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.transactionTime && params.transactionTime.length > 0) {
        params.startTransactionDate = params.transactionTime[0];
        params.endTransactionDate = params.transactionTime[1];
        delete params.transactionTime;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      let isEmpty = true;
      Object.keys(this.search).forEach((x) => {
        if (this.search[x] != null && this.search[x] != '') {
          isEmpty = false;
        }
      });
      if (!isEmpty) {
        this.loading = true;
        delete params.operatorName;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      } else {
        this.$message({
          type: 'warning',
          message: '请输入至少一个查询条件!'
        });
        this.loading = false;
        this.page.total = 0;
        this.data = [];
      }
    },
    /**
     * 打开操作人员列表模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择操作人员（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          {
            label: '所属角色',
            prop: 'roleName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      if (this.modalName === 'userModal') {
        this.search.operator = this._get(rowData, 'id', '');
        this.search.operatorName = this._get(rowData, 'realName', '');
      }
    }
  }
};
</script>

<style></style>
